#include <unistd.h>
#include <stdio.h>
#include <string.h>



#include "zxing.h"
using namespace zxing;


extern "C" int zxing_scan_qrcode(int width, int height, unsigned char *ydata, char *stack, int stacklen)
{
        int result = 0;

        unsigned char *yres = (unsigned char *) (ydata);
        int const rectX = 0;
        int const rectY = 0;
        int const rectWidth = width;
        int const rectHeight = height;

        Ref<GreyscaleLuminanceSource> luminanceSource(
                        new GreyscaleLuminanceSource(yres, width, height, rectX, rectY, rectWidth, rectHeight));

        Ref<Binarizer> binarizer(new HybridBinarizer(luminanceSource));
        Ref<BinaryBitmap> bitmap(new BinaryBitmap(binarizer));
        Ref<qrcode::QRCodeReader> reader(new qrcode::QRCodeReader());

        DecodeHints decodeHints;
        decodeHints.addFormat(BarcodeFormat_QR_CODE);
//      decodeHints.addFormat(BarcodeFormat_DATA_MATRIX);
//      decodeHints.addFormat(BarcodeFormat_UPC_E);
//      decodeHints.addFormat(BarcodeFormat_UPC_A);
//      decodeHints.addFormat(BarcodeFormat_EAN_8);
//      decodeHints.addFormat(BarcodeFormat_EAN_13);
//      decodeHints.addFormat(BarcodeFormat_CODE_128);
//      decodeHints.addFormat(BarcodeFormat_CODE_39);
//      decodeHints.addFormat(BarcodeFormat_ITF);

		try {

			Ref<Result> Result(reader->decode(bitmap, decodeHints));
			Ref<String> ResultText(Result->getText());

			result = snprintf(stack, stacklen, "%s", ResultText->getText().c_str());
			//akspc_log_tag_debug2("TUYA", "ZXING %s Detected.", stack);

		} catch (...) {
			result = -1;
		}

		return result;
}


